import React from 'react';
import Icon from '../Icon/Icon.jsx';
import './index.scss';
import avatar from './avatar.jpg';

export default class extends React.Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
        this.imageRef = React.createRef();
        this.reader = new FileReader();
        this.reader.onload = (e) => {

            this.imageRef.current.src = e.currentTarget.result;

        }
    }
    onClick = (e) => {
        this.inputRef.current.click();
    }

    onFileChange = (e) => {
        const { onChange } = this.props;
        const file = e.currentTarget.files[0];
        this.reader.readAsDataURL(file);
        onChange && onChange(file);
    }

    render() {
        const { name = '', className='', isAvatar=true } = this.props;
        return (
            <div className={`okay-uploader ${className}`} onClick={this.onClick}>
                <input type="file" name={name} ref={this.inputRef} onChange={this.onFileChange}/>
                {isAvatar && <img className="okay-uploader-avatar" src={avatar} ref={this.imageRef}/>}
                {!isAvatar && <Icon type="add" color="#777777"/>}

            </div>
        )
    }
}
